package com;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@WebServlet(name = "LoginServlet" ,value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
  static Map<String,String> login=new HashMap<String,String>();

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      response.setContentType("text/html;charset=utf-8");
      login.put("username","张三");
      String username= String.valueOf(request.getParameter("username"));
      if(username=="")
          response.getWriter().println("请输入用户名登录");
      boolean user= Objects.equals(username, login.get("username"));

//      System.out.println(Arrays.toString(request.getCookies()));
      if (user&&request.getParameter("dl")==null){
          Cookie cookie=new Cookie("username", (String) request.getParameter("username"));
          cookie.setPath(request.getContextPath()+"/login.jsp");
          cookie.setMaxAge(60*60);
          response.addCookie(cookie);
          response.getWriter().println("欢迎张三，你已登录"+"<a href=login.jsp>退出</a>");
      } else if (user&&request.getParameter("dl")!=null) {
          Cookie cookie=new Cookie("username", (String) request.getParameter("username"));
          cookie.setPath(request.getContextPath()+"/login.jsp");
          cookie.setMaxAge(60*60);
          response.addCookie(cookie);
          Cookie cookie1=new Cookie("dl", (String) request.getParameter("dl"));
          cookie1.setPath(request.getContextPath()+"/login.jsp");
          cookie1.setMaxAge(60*60);
          response.addCookie(cookie1);
          response.getWriter().println("欢迎张三，你已登录"+"<a href=login.jsp>退出</a>");
      } else if(!user){
          response.getWriter().println("用户名错误");
      }

  }
  public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {
      this.doGet(request,response);
  }

}
